<template>
    <CustomMask v-model:show="visible" width="100%">
        <div class="popup-box">
            <NuxtIcon name="close" class="close" @click="close"></NuxtIcon>
            <div class="s-1" v-if="step === 0">
                <div class="s-1-t">
                    <img :src="publicUrl('/img/star.png')" />
                    <span class="t">{{transl('预约睇楼团')}}</span>
                    <img :src="publicUrl('/img/star.png')" />
                </div>
                <div class="s-1-b">
                    <div class="le-ipt">
                        <span class="label">{{transl('您的称呼')}}</span>
                        <input v-model="form.name" :placeholder="transl('请输入您的称呼')" />
                    </div>
                    <div class="le-ipt">
                        <div class="le-pr">
                            <span @click="isOpen = true">+{{ prefix[nowPrefix] }}</span>
                            <NuxtIcon name="open" @click="isOpen = true"></NuxtIcon>
                            <div ref="codeRef" class="choose-code" v-show="isOpen">
                                <div @click="choose(index)" class="code-item" v-for="(p, index) in prefix" :key="index">{{ p
                                }}</div>
                            </div>
                        </div>
                        <input :placeholder="transl('请输入您的电话')" type="tel" v-model="form.phone" />
                    </div>
                    <div class="le-baoming" @click="nextStep">
                        <span> {{transl('立即报名')}}</span>
                    </div>
                </div>
            </div>
            <div class="s-2" v-else>
                <div class="s-2-sub">
                    {{transl('为确保你是本人操作')}}
                </div>
                <div class="s-2-title">
                    {{transl("我们已经发送了验证码到您的手机")}}
                </div>
                <div class="s-2-phone">
                    {{ tuoMin(newPhone) }}
                </div>
                <div class="le-ipt my-ipt">
                    <span class="label">{{transl("验证码")}}:</span>
                    <input maxlength="4" v-model="form.code" :placeholder="transl('请输入验证码')" />
                    <div class="code" @click="th_sendCode">{{ transl(timeC.maxCount === timeC.nowCount ? '获取验证码' :
                        `${timeC.nowCount}s后重新获取`) }}</div>
                </div>
                <div class="le-baoming submit" @click="th_submit">
                    <span> {{transl('确认提交')}}</span>
                </div>
            </div>
        </div>
    </CustomMask>
</template>
    
<script setup lang='ts'>
import CustomMask from "@/views/components/CustomMask/index.vue"
import { ref, watch } from "vue";
import { publicUrl, throttle } from "@/utils/index"
import { tuoMin } from "@/utils/util"
import { onClickOutside } from "@vueuse/core"
import type { SubmitForm } from "@/api/interface/site"
import validateRule from "~/utils/validate";
import { send } from "~/api/modules/code";
import { clue, valid } from "~/api/modules/index";
import { LangStore } from "@/stores/modules/lang"
const { transl } = LangStore()
const { $message } = useNuxtApp()
interface Props {
    show: boolean;
}
const form = ref<SubmitForm>({ phone: "", name: "" })
const newPhone = ref("")
const emits = defineEmits(['update:show'])
const visible = ref(false)
const props = withDefaults(defineProps<Props>(), { show: false })
watch(() => props.show, () => { visible.value = props.show })
watch(() => visible.value, () => { emits('update:show', visible.value) })

const step = ref(0)

const prefix = reactive<string[]>(["852", "86", "853"])
const nowPrefix = ref(0)
const isOpen = ref(false)

const codeRef = ref(null)
onClickOutside(codeRef, () => {
    isOpen.value = false
})
const choose = (index: number) => {
    nowPrefix.value = index
    isOpen.value = false
}
const close = () => {
    newPhone.value = ""
    form.value = {
        phone: "",
        code: "",
        name: ""
    }
    step.value = 0
    visible.value = false
}
const sendCode = async () => {
    if (!validateRule(newPhone.value, 'phone')) return $message.error("手机格式不正确", '16px')
    newPhone.value = nowPrefix.value == 1 ? JSON.stringify(JSON.parse(form.value.phone)) : prefix[nowPrefix.value] + form.value.phone
    if (timeC.maxCount !== timeC.nowCount) return
    try {
        await send({ phone: newPhone.value })
        count()
        $message.success("发送成功", "16px")
    } catch (error) {

    }
}
const th_sendCode = throttle(sendCode, 1000)
const nextStep = async () => {
    newPhone.value = nowPrefix.value == 1 ? JSON.stringify(JSON.parse(form.value.phone)) : prefix[nowPrefix.value] + form.value.phone
    if (!validateRule(newPhone.value, 'phone')) return $message.error("手机格式不正确", '16px')
    if (!form.value.name) return $message.error("请填写您的称呼", '16px')
    if (form.value.name.length > 10) return $message.error("您的称呼超过10个字了", '16px')
    try {
        console.log("aksdkaksdkakdaksdk")
        await clue({ phone: newPhone.value, name: form.value.name })
        step.value = 1
        count()
    } catch (error) {
        console.log(error)
    }
}
const count = () => {
    if (timeC.maxCount !== timeC.nowCount) return
    timeC.nowCount--
    timeC.timer = setInterval(() => {
        timeC.nowCount--
        if (timeC.nowCount < 1) {
            timeC.nowCount = timeC.maxCount
            clearInterval(timeC.timer as NodeJS.Timeout)
        }
    }, 1000)
}
const timeC = reactive<{ maxCount: number; nowCount: number; timer: NodeJS.Timer | null }>({
    maxCount: 60,
    nowCount: 60,
    timer: null
})
const acceptParams = async (params: SubmitForm) => {
    form.value = JSON.parse(JSON.stringify(params))
    newPhone.value = form.value.phone
    step.value = 1
    try {
        await clue({ phone: newPhone.value, name: form.value.name })
        step.value = 1
        count()
    } catch (error) {

    }
}

const submit = async () => {
    if (!validateRule(form.value.phone, 'phone')) return $message.error("手机格式不正确", '16px')
    if (!form.value.name) return $message.error("请填写您的称呼", "16px")
    if (form.value.name.length > 10) return $message.error("您的称呼超过10个字了", "16px")
    if (!form.value.code) return $message.error('请输入验证码', "16px")
    try {
        await valid({ phone: newPhone.value, code: form.value.code, name: "" })
        $message.success("提交成功", "16px")
        step.value = 0
        visible.value = false
        timeC.nowCount = timeC.maxCount
        clearInterval(timeC.timer as NodeJS.Timeout)
    } catch (error) {
        $message.error((error as any).msg,"16px")
    }
}

const th_submit = throttle(submit, 1000)

defineExpose({ acceptParams })
</script>
    
<style scoped lang="scss">
@import "./index.scss";
</style>